package cn.itsource.service.system.imp;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.jwt.JwtUtil;
import cn.itsource.jwt.Payload;
import cn.itsource.mapper.system.LogininfoMapper;
import cn.itsource.service.system.ILogininfoService;

import cn.itsource.system.domain.LoginDto;
import cn.itsource.system.domain.Logininfo;
import cn.itsource.system.domain.Menu;
import cn.itsource.utils.BusinessException;
import cn.itsource.utils.JsonResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class LogininfoService implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;


    @Override
    public String accountLogin(LoginDto loginDto) throws BusinessException {
        String username =loginDto.getUserName();
        String password =loginDto.getPassword();
        Integer type =loginDto.getType();
        System.out.println(loginDto);

        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            throw new BusinessException("参数不能为空");
        }
        Logininfo logininfo1 = logininfoMapper.findByAccount(loginDto);
        if(logininfo1==null){
            throw  new BusinessException("账号不存在");
        }
        String salt = logininfo1.getSalt();
        String md5 = SecureUtil.md5(salt + password);
        if (!md5.equals(logininfo1.getPassword())) {
            throw new BusinessException("密码不正确");
        }
        if(!logininfo1.getDisable()){
            throw new BusinessException("账号禁用");
        }
        Payload payload = new Payload();
        payload.setLogininfo(logininfo1);
        if(logininfo1.getType()==0){
            //获取用户的权限信息
            List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo1.getId());
            //获取用户的菜单信息
            //List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
            List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo1.getId());
            payload.setPermissions(permissions);
            payload.setMenus(menus);

        }


        String token = JwtUtil.generateToken(payload);
        return token;

    }

    public static void main(String[] args) {
        String s = RandomUtil.randomString(32);
        System.out.println(s);
        String a="123456";
        String md5 = SecureUtil.md5(s + a);
        System.out.println(md5);
    }
}
